package com.yvon.maple.service.auth.valicode.validate.code.processor;

import cn.hutool.core.util.StrUtil;
import com.yvon.boot.common.result.GlobalException;
import com.yvon.maple.service.auth.valicode.validate.code.repository.CodeRepository;
import com.yvon.maple.service.auth.valicode.vo.CodeVo;
import com.yvon.maple.service.auth.vo.ValidateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author : Yvon
 * @since : 2021-08-24
 */
@Component
public class DefaultCodeValidator implements CodeValidator{

    @Autowired
    private CodeRepository codeRepository;

    @Override
    public boolean validate(ValidateVo vo) {

        String code = vo.getCode();
        String key = vo.getKey();
        String grantType = vo.getCodeType().getType();
        String name = vo.getCodeType().getName();

        if (StrUtil.isEmpty(code) || StrUtil.isEmpty(key)) {
            throw new GlobalException(name+"不能为空");
        }
        CodeVo codeVo = codeRepository.get(grantType, key);
        if (Objects.isNull(codeVo)) {
            throw new GlobalException("获取"+name+"的值失败");
        }

        if (codeVo.isExpire()) {
            codeRepository.remove(grantType, key);
            throw new GlobalException(name+ "已过期");
        }

        if (!StrUtil.equals(codeVo.getCode().toLowerCase(), code.toLowerCase())) {
            throw new GlobalException(name+"不匹配");
        }

        codeRepository.remove(grantType, key);

        return true;
    }
}
